<?php
class ControllerStep3 extends Controller {
    private $error = array();

    public function index() {
        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {

            $output  = '<?php' . "\n";
            $output .= 'define(\'DIR_SYSTEM\', \'' . $this->load->get_path('dir_root'). 'system/\');' . "\n";

            $file = fopen($this->load->get_path('dir_root') . 'config.php', 'w');
            fwrite($file, $output);
            fclose($file);

            $file = fopen($this->load->get_path('dir_root') . 'admin/config.php', 'w');
            fwrite($file, $output);
            fclose($file);

            // System Config
            $cfg = new Config($this->load->get_path('dir_config') . 'system.ini');
            $cfg->set_section('system')
                ->set('http_server' ,     HTTP_SERVER)
                ->set('https_server' ,    HTTPS_SERVER)
                ->set('error_display',  true)
                ->set('error_log',      true)
                ->set('seo_url',        false)
                ->set('error_filename', 'error.txt');

            $cfg->set_section('paths')
                ->set('dir_system',     $this->load->get_path('dir_root') . 'system/')
                ->set('dir_logs',       $this->load->get_path('dir_root') . 'system/logs/')
                ->set('dir_config',     $this->load->get_path('dir_root') . 'system/config/')
                ->set('dir_cache',      $this->load->get_path('dir_root') . 'system/cache/')
                ->set('dir_library',    $this->load->get_path('dir_root') . 'library/')
                ->set('dir_image',      $this->load->get_path('dir_root') . 'image/')
                ->set('dir_download',   $this->load->get_path('dir_root') . 'download/');

            $cfg->set_section('database')
                ->set('db_driver',  addslashes($this->request->post['db_driver']))
                ->set('db_host', addslashes($this->request->post['db_host']))
                ->set('db_user', addslashes($this->request->post['db_user']))
                ->set('db_password', addslashes($this->request->post['db_password']))
                ->set('db_name', addslashes($this->request->post['db_name']))
                ->set('db_prefix',addslashes($this->request->post['db_prefix']));

            if(!$cfg->save()){
                $this->error['warning'] = 'Warning: Failed to save system.ini';
            }

            // Catalog Config
            $cfg = new Config($this->load->get_path('dir_config') . 'catalog.ini');

            $cfg->set_section('app')
                ->set('id', 'catalog')
                ->set('classname', 'app_catalog')
                ->set('filename', 'catalog.php')
                ->set('bootstrap', 'bootstrap.php');

            $cfg->set_section('config')
                ->set('theme',          'default')
                ->set('http_server',     HTTP_SERVER)
                ->set('https_server',    HTTPS_SERVER);

            $cfg->set_section('actions')
                ->set('error', 'error/not_found')
                ->set('default', 'common/home');

            $cfg->set_section('pre_actions')
                ->set('seo', 'common/seo_url')
                ->set('maintenance', 'common/maintenance');

            $cfg->set_section('paths')
                ->set('dir_app',          $this->load->get_path('dir_root') . 'catalog/')
                ->set('dir_template',     $this->load->get_path('dir_root') . 'catalog/view/theme/')
                ->set('dir_language',     $this->load->get_path('dir_root') . 'catalog/language/');

            if(!$cfg->save()){
                $this->error['warning'] = 'Warning: Failed to save catalog.ini';
            }

            // Admin Config
            $cfg = new Config($this->load->get_path('dir_config') . 'admin.ini');

            $cfg->set_section('app')
                ->set('id', 'admin')
                ->set('classname', 'app_admin')
                ->set('filename', 'admin.php')
                ->set('bootstrap', 'bootstrap.php');

            $cfg->set_section('config')
                ->set('http_server',     HTTP_SERVER . 'admin/')
                ->set('https_server',    HTTPS_SERVER . 'admin/')
                ->set('http_catalog',    HTTP_SERVER)
                ->set('https_catalog',   HTTPS_SERVER);

            $cfg->set_section('actions')
                ->set('error', 'error/not_found')
                ->set('default', 'common/home');

            $cfg->set_section('pre_actions')
                ->set('login', 'common/home/login')
                ->set('permission', 'common/home/permission');

            $cfg->set_section('paths')
                ->set('dir_app',         $this->load->get_path('dir_root') . 'admin/')
                ->set('dir_system',      $this->load->get_path('dir_root') . 'system/')
                ->set('dir_template',    $this->load->get_path('dir_root') . 'admin/view/')
                ->set('dir_language',    $this->load->get_path('dir_root') . 'admin/language/')
                ->set('dir_catalog',     $this->load->get_path('dir_root') . 'catalog/');

            if(!$cfg->save()){
                $this->error['warning'] = 'Warning: Failed to save admin.ini';
            }

            if(!$this->error){
                // Database install
                $this->app->model('install', true, true);
                $this->model_install->mysql($this->request->post);
                $this->redirect($this->url->link('step_4'));
            }
        }

        if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } else {
            $this->data['error_warning'] = '';
        }

        if (isset($this->error['db_host'])) {
            $this->data['error_db_host'] = $this->error['db_host'];
        } else {
            $this->data['error_db_host'] = '';
        }

        if (isset($this->error['db_user'])) {
            $this->data['error_db_user'] = $this->error['db_user'];
        } else {
            $this->data['error_db_user'] = '';
        }

        if (isset($this->error['db_name'])) {
            $this->data['error_db_name'] = $this->error['db_name'];
        } else {
            $this->data['error_db_name'] = '';
        }

        if (isset($this->error['db_prefix'])) {
            $this->data['error_db_prefix'] = $this->error['db_prefix'];
        } else {
            $this->data['error_db_prefix'] = '';
        }

        if (isset($this->error['username'])) {
            $this->data['error_username'] = $this->error['username'];
        } else {
            $this->data['error_username'] = '';
        }

        if (isset($this->error['password'])) {
            $this->data['error_password'] = $this->error['password'];
        } else {
            $this->data['error_password'] = '';
        }		

        if (isset($this->error['email'])) {
            $this->data['error_email'] = $this->error['email'];
        } else {
            $this->data['error_email'] = '';
        }	

        $this->data['action'] = $this->url->link('step_3');

        $this->data['pdo_driver'] = PDO::getAvailableDrivers();

        // Try to load configuration 
        $db_cfg = new Config($this->load->get_path('dir_config') . 'system.ini');
        $db_cfg->parse();
        $db_cfg->set_section('database');

        if (isset($this->request->post['db_driver'])) {
            $this->data['db_driver'] = $this->request->post['db_driver'];
        } elseif($db_cfg->has('db_driver')){
            $this->data['db_driver'] = $db_cfg->get('db_driver'); 
        }else{
            $this->data['db_driver'] = 'mysql';
        }

        if (isset($this->request->post['db_host'])) {
            $this->data['db_host'] = $this->request->post['db_host'];
        } elseif($db_cfg->has('db_host')){
            $this->data['db_host'] = $db_cfg->get('db_host'); 
        } else {
            $this->data['db_host'] = 'localhost';
        }

        if (isset($this->request->post['db_user'])) {
            $this->data['db_user'] = html_entity_decode($this->request->post['db_user']);
        } elseif($db_cfg->has('db_user')){
            $this->data['db_user'] = $db_cfg->get('db_user'); 
        } else {
            $this->data['db_user'] = '';
        }

        if (isset($this->request->post['db_password'])) {
            $this->data['db_password'] = html_entity_decode($this->request->post['db_password']);
        } elseif($db_cfg->has('db_password')){
            $this->data['db_password'] = $db_cfg->get('db_password'); 
        } else {
            $this->data['db_password'] = '';
        }

        if (isset($this->request->post['db_name'])) {
            $this->data['db_name'] = html_entity_decode($this->request->post['db_name']);
        } elseif($db_cfg->has('db_name')){
            $this->data['db_name'] = $db_cfg->get('db_name'); 
        } else {
            $this->data['db_name'] = '';
        }

        if (isset($this->request->post['db_prefix'])) {
            $this->data['db_prefix'] = html_entity_decode($this->request->post['db_prefix']);
        } elseif($db_cfg->has('db_prefix')){
            $this->data['db_prefix'] = $db_cfg->get('db_prefix'); 
        } else {
            $this->data['db_prefix'] = 'prefix_';
        }

        if (isset($this->request->post['username'])) {
            $this->data['username'] = $this->request->post['username'];
        } else {
            $this->data['username'] = 'admin';
        }

        if (isset($this->request->post['password'])) {
            $this->data['password'] = $this->request->post['password'];
        } else {
            $this->data['password'] = '';
        }

        if (isset($this->request->post['email'])) {
            $this->data['email'] = $this->request->post['email'];
        } else {
            $this->data['email'] = '';
        }

        $this->data['back'] = $this->url->link('step_2');

        $this->template = 'step_3.tpl';
        $this->children = array(
            'header',
            'footer'
        );

        $this->response->setOutput($this->render());		
    }

    private function validate() {
        if (!$this->request->post['db_host']) {
            $this->error['db_host'] = 'Host required!';
        }

        if (!$this->request->post['db_user']) {
            $this->error['db_user'] = 'User required!';
        }

        if (!$this->request->post['db_name']) {
            $this->error['db_name'] = 'Database Name required!';
        }

        if ($this->request->post['db_prefix'] && preg_match('/[^a-z0-9_]/', $this->request->post['db_prefix'])) {
            $this->error['db_prefix'] = 'DB Prefix can only contain lowercase characters in the a-z range, 0-9 and "_"!';
        }

        if (!$this->error) {    

            try { 
                $db = new database($this->request->post['db_driver'],
                    $this->request->post['db_host'],
                    $this->request->post['db_user'],
                    $this->request->post['db_password'],
                    $this->request->post['db_name']);
            } catch (PDOException $e) {
                $this->error['warning'] = $e->getMessage();
            }
        }

        if (!$this->request->post['username']) {
            $this->error['username'] = 'Username required!';
        }

        if (!$this->request->post['password']) {
            $this->error['password'] = 'Password required!';
        }

        if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email'])) {
            $this->error['email'] = 'Invalid E-Mail!';
        }

        if (!is_writable($this->load->get_path('dir_root') . 'config.php')) {
            $this->error['warning'] = 'Error: Could not write to config.php please check you have set the correct permissions on: ' . $this->load->get_path('dir_root') . 'config.php!';
        }

        if (!is_writable($this->load->get_path('dir_root') . 'admin/config.php')) {
            $this->error['warning'] = 'Error: Could not write to admin/config.php please check you have set the correct permissions on: ' . $this->load->get_path('dir_root') . 'admin/config.php!';
        }	

        if (!$this->error) {
            return true;
        } else {
            return false;
        }		
    }
}
?>
